package com.yiwyn;


import com.yiwyn.domain.Context;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.io.*;
import java.nio.file.*;
import java.util.Scanner;

public class Main {


    public static void main(String[] args) throws IOException {


        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();


        Context c = new Context();
        c.setCtxName(s);
        c.setWritePath("module-generater-demo/src/main/java/com/yiwyn/impl/test");

        StandardEvaluationContext context = new StandardEvaluationContext();
        context.setVariable("ctx", c);

        InputStream interTemplateIs = ClassLoader.getSystemResourceAsStream("template/CustHandleImp.java");
        InputStreamReader interTemplateReader = new InputStreamReader(interTemplateIs);
        BufferedReader interTemplate = new BufferedReader(interTemplateReader);

        // 获取path路径
        Path path = Paths.get(c.getWritePath() + "/" + c.getCtxName() + "HandleImpl.java");
        // 根据path 创建文件夹
        Files.createDirectories(path.getParent());
        OutputStream out = Files.newOutputStream(path);
        // 创建写入流
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(out);
        // 增强流
        BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);


        String line;
        while ((line = interTemplate.readLine()) != null) {
            line = line.replace("{#ctx.ctxName}", replace(context, "{#ctx.ctxName}"));
            System.out.println(line);

            bufferedWriter.write(line);
            bufferedWriter.newLine();
        }
        bufferedWriter.flush();
    }

    public static String replace(StandardEvaluationContext context, String express) {
        ExpressionParser parser = new SpelExpressionParser();
        Expression expression = parser.parseExpression(express);
        return expression.getValue(context, String.class);
    }


}
